package com.major.dawn.leetCode.string;

public class StrToInt {

    final char space_empty = ' ';
    final char plus = '+';
    final char minus = '-';
    final char point = '.';
    final int boundary = Integer.MAX_VALUE / 10;
// 写一个函数 StrToInt，实现把字符串转换成整数这个功能。不能使用 atoi 或者其他类似的库函数。

    //    关键的地方在于数值是否越界
    public int strToInt(String str) {
//      正负号标识
        int sign = 1;
        int cul = 0;
        int firstIndex = 0;

        if (str == null || str.equals("")) {
            return 0;
        }


        char[] chars = str.toCharArray();

        int length = chars.length;


        for (int i = 0; i < length; i++) {
            char aChar = chars[i];

            //        找到第一个有效字符
            int parseInt = charParseInt(aChar);
            if (firstIndex == 0) {
                if (aChar != space_empty) {
                    if (aChar == minus || aChar == plus) {
                        firstIndex = 1;
                        if (aChar == minus) {
                            sign = -1;
                        }
                        continue;
                    }
                    if (aChar > 47 && aChar < 58) {
                        firstIndex = 1;
                        cul = parseInt;
                        continue;
                    }
                    break;
                }
            } else {
                if (aChar > 47 && aChar < 58) {
//                        判断继续添加是否会越界
//                        计算新值
                    if (cul < boundary || (cul == boundary && parseInt < 8)) {
                        cul = cul * 10 + parseInt;
                        continue;
                    }

                    if (sign == 1) {
                        return Integer.MAX_VALUE;
                    } else {
                        return Integer.MIN_VALUE;
                    }
                }else {
                    break;
                }

            }
        }


        return sign * cul;
    }

    private int charParseInt(char aChar) {
        return aChar - 48;
    }


    public static void main(String[] args) {
        StrToInt strToInt = new StrToInt();
        int i = strToInt.strToInt(" -42");
        System.out.println(i);

    }

}
